package com.ruoyi.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.enums.AuditStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.crm.domain.CrmContract;
import com.ruoyi.crm.domain.CrmOrder;
import com.ruoyi.crm.domain.CrmOrderCollectPayMoney;
import com.ruoyi.crm.domain.dto.CrmContractDTO;
import com.ruoyi.crm.domain.dto.CrmProjectDTO;
import com.ruoyi.crm.domain.dto.CrmStatisticsSearchDTO;
import com.ruoyi.crm.mapper.*;
import com.ruoyi.crm.service.ICrmDataStatisticsService;
import com.ruoyi.crm.service.ICrmOrderService;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author YanWenliang
 * @date 2024/12/20 10:10
 * @desciption: 数据统计
 */

@Service
public class CrmDataStatisticsServiceImpl implements ICrmDataStatisticsService {

    @Autowired
    private CrmDataStatisticsMapper crmDataStatisticsMapper;

    @Autowired
    private CrmTaskMapper crmTaskMapper;

    @Autowired
    private CrmOrderCollectPayMoneyMapper crmOrderCollectPayMoneyMapper;

    @Autowired
    private CrmOrderPayDetailsMapper crmOrderPayDetailsMapper;


    @Autowired
    private CrmOrderCollectDetailsMapper crmOrderCollectDetailsMapper;

    /**
     * 统计商机数量、待续费数据
     * @return
     */
    @Override
    public Map<String, Integer> statisticsProjectNumberAndTodoAndRenewed() {
        // 获取商机数量以及待续费数量
        Map<String,Integer> orderCountMap = crmDataStatisticsMapper.getOrderAndIsRenewalCount(SecurityUtils.getUserId());
        return orderCountMap;
    }

    /**
     * 统计业绩数据
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public Map<String, BigDecimal> statisticsPerformance(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {

        Map<String, BigDecimal> resultMap = new HashMap<>();

        // 统计合同金额
        BigDecimal contractMoneySum = crmDataStatisticsMapper.getContractMoneySum(crmStatisticsSearchDTO);

        resultMap.put("contractMoney", contractMoneySum);

        // 统计90，60，30
        Map<String, BigDecimal> performanceMap = crmDataStatisticsMapper.getPerformance(crmStatisticsSearchDTO);

        if (ObjectUtil.isNotEmpty(performanceMap)){
            resultMap.putAll(performanceMap);
        }

        // 固定支出
        BigDecimal fixedPayout = BigDecimal.ZERO;
        // 计算现金流(现金流只计算组和部门)
        if (StringUtils.isEmpty(crmStatisticsSearchDTO.getUserId())){
            fixedPayout = crmDataStatisticsMapper.getFixedPayout(crmStatisticsSearchDTO);
            // 计算回款
            BigDecimal payment = crmDataStatisticsMapper.getPayment(crmStatisticsSearchDTO);
            // 计算现金流
            BigDecimal cashFlow = payment.subtract(fixedPayout);
            resultMap.put("cashFlow", cashFlow);
        }

        // 计算预计利润
        BigDecimal profit = crmDataStatisticsMapper.getProfitAndCommission(crmStatisticsSearchDTO);
        // 计算实际利润
        BigDecimal realProfit = crmDataStatisticsMapper.getRealProfit(crmStatisticsSearchDTO);

        profit.add(realProfit);
        profit = profit.subtract(fixedPayout);
        // 计算预计提成
        BigDecimal commission = ObjectUtil.isNotEmpty(profit) ? profit.multiply(new BigDecimal(0.15)).setScale(2, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO;

        resultMap.put("profit", profit);
        resultMap.put("commission", commission);


        return resultMap;
    }

    /**
     * 统计实际支出数据
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public Map<String, BigDecimal> statisticsActualSpending(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.statisticsActualSpending(crmStatisticsSearchDTO);
    }

    /**
     * 统计待办数据数量
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public Map<String, Object> statisticsToDo(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        Map<String, Object> resultMap = new HashMap<>();

        // 统计待成交、待验收、待结算待跟进数据
        Map<String, Integer> orderCount = crmDataStatisticsMapper.getOrderCountGroupProgess(crmStatisticsSearchDTO);
        if (ObjectUtil.isNotEmpty(orderCount)) {
            resultMap.putAll(orderCount);
        }

        // 统计应收为收
        BigDecimal collectionAmt = crmDataStatisticsMapper.getCollectionAmt(crmStatisticsSearchDTO);
        resultMap.put("collectionAmt", collectionAmt);


        // 统计应付未付
        BigDecimal payAmt = crmDataStatisticsMapper.getPayAmt(crmStatisticsSearchDTO);
        resultMap.put("payAmt", payAmt);

        return resultMap;
    }


    /**
     * 销售额排行
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmContractDTO> statisticsSales(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.statisticsSales(crmStatisticsSearchDTO);
    }

    /**
     * 成交次数客户排行
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmContractDTO> statisticsTransactionsCount(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.statisticsTransactionsCount(crmStatisticsSearchDTO);
    }

    /**
     * 统计商机数量、待续费列表数据
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmOrder> getOrderAndIsRenewalList(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.getOrderAndIsRenewalList(crmStatisticsSearchDTO);
    }

    /**
     * 统计合同列表
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmProjectDTO> getContractMoneySumList(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        List<CrmProjectDTO> contractMoneySumList = crmDataStatisticsMapper.getContractMoneySumList(crmStatisticsSearchDTO);
        contractMoneySumList.forEach(item -> {
            BigDecimal actualDay = crmTaskMapper.getActualDay(item.getOrderId(), item.getCustomerId(),item.getUserId());
            item.setActualTaskCount(ObjectUtil.isNull(actualDay) ? BigDecimal.ZERO : actualDay);
            //查询收付款 审核通过的
            List<CrmOrderCollectPayMoney> collectPayMonies = crmOrderCollectPayMoneyMapper.selectList(new LambdaQueryWrapper<CrmOrderCollectPayMoney>()
                    .eq(CrmOrderCollectPayMoney::getOrderId, item.getOrderId())
                    .eq(CrmOrderCollectPayMoney::getCustomerId, item.getCustomerId())
                    .eq(CrmOrderCollectPayMoney::getAuditStatus, AuditStatus.PASS.getCode()));
            //收款未付
            BigDecimal collectDetailsAmounts = getCollectMoneyByCollectPayMonies(collectPayMonies);
            item.setAwaitCollection(collectDetailsAmounts);
            //付款未付
            BigDecimal payDetailsAmounts = getPayMoneyByCollectPayMonies(collectPayMonies);
            item.setAccountAmt(payDetailsAmounts);
        });
        return contractMoneySumList;
    }


    /**
     * 统计90，60，30 数据列表
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmOrder> getPerformanceList(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.getPerformanceList(crmStatisticsSearchDTO);
    }

    /**
     * 付款列表
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmOrderCollectPayMoney> getPayAmtList(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.getPayAmtList(crmStatisticsSearchDTO);
    }

    /**
     * 收款列表
     * @param crmStatisticsSearchDTO
     * @return
     */
    @Override
    public List<CrmOrderCollectPayMoney> getCollectionAmtList(CrmStatisticsSearchDTO crmStatisticsSearchDTO) {
        return crmDataStatisticsMapper.getCollectionAmtList(crmStatisticsSearchDTO);
    }

    private BigDecimal getPayMoneyByCollectPayMonies(List<CrmOrderCollectPayMoney> collectPayMonies) {
        if (StringUtils.isNotEmpty(collectPayMonies)) {
            Map<String, List<CrmOrderCollectPayMoney>> map = collectPayMonies.stream().collect(Collectors.groupingBy(CrmOrderCollectPayMoney::getMoneyType));
            //收款容器
            List<CrmOrderCollectPayMoney> collectList = map.get("1");
            if (StringUtils.isNotEmpty(collectList)) {
                List<String> ids = collectList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
                return crmOrderCollectDetailsMapper.getCollectMoney(ids);
            }
        }
        return BigDecimal.ZERO;
    }


    private BigDecimal getCollectMoneyByCollectPayMonies(List<CrmOrderCollectPayMoney> collectPayMonies) {
        if (StringUtils.isNotEmpty(collectPayMonies)) {
            Map<String, List<CrmOrderCollectPayMoney>> map = collectPayMonies.stream().collect(Collectors.groupingBy(CrmOrderCollectPayMoney::getMoneyType));
            //付款容器
            List<CrmOrderCollectPayMoney> payList = map.get("0");
            if (StringUtils.isNotEmpty(payList)) {
                List<String> ids = payList.stream().map(CrmOrderCollectPayMoney::getCollectPayMoneyId).collect(Collectors.toList());
                return crmOrderPayDetailsMapper.getPayMoney(ids);
            }
        }
        return BigDecimal.ZERO;
    }


}
